﻿<?php
error_reporting(E_ALL);
//一种将HTML视图文件写入word的方法
 class Word2003
{ 
	private $path;
	public function __construct($val="temp.doc")
	{
		$val=trim($val);
		if(!preg_match('/.+?[.]doc$/',$val)){
			echo $val;
			$val.='.doc';
			echo $val;
		}
		$this->path=$val;
		@ob_flush();//每次执行前刷新缓存 
		@flush(); 
		ob_start();
		echo '<html xmlns:o="urn:schemas-microsoft-com:office:office"
		xmlns:w="urn:schemas-microsoft-com:office:word"
		xmlns="http://www.w3.org/TR/REC-html40">';
	}
	public function save()
	{
	 	echo "</html>";
		$data = ob_get_contents();
		ob_end_clean();	 
		$this->writefile ($this->path,$data);
	}
 
	function writefile ($filename,$data)
	{
		@$fp=fopen($filename,"w");
		if(!$fp || !@fwrite($fp,$data)){
			echo "Save failed:".$php_errormsg."<br/>";
			return;
		}
		fclose($fp);
	}
}





/*
//测试:批量生成
define('N',1);
for($i=1;$i<=N;$i++){ 
    $word = new Word2003('test'.$i.'.doc'); 
    echo $contents; 
    $word->save(); 
}

*/
/*
导出格式:
期刊:[序号]作者.篇名.刊名，出版年份，卷号(期号):起止页码.
会议:标题.作者1,作者2,[...].会议名.会议地点.会议时间.
*/


function saveToWord($contents,$col_del,$export_path)
{

	$word=new Word2003($export_path);
	$cont="<body>\n";
	$index=0;
	foreach($contents as $row)
	{
		$index+=1;
		$oneRecord="";
		$last_del="";
		foreach($col_del as $column=>$del)
		{
			if(!empty($row[$column])){
				if($column=='页码')
					$row[$column]="pp:".$row[$column];
				$oneRecord.=empty($oneRecord)?"":$last_del;
				$oneRecord.=$row[$column];
				$last_del=$del;//保存分隔符
			}	
		}
		/*
				$cont.="[$index] ".trim($row['标题']).".";
			//author
			$number=array('一','二','三','四','五','六','七','八','九','十');
			foreach($number as $val){
				$val="第".$val."作者";
				if(!empty($row[$val])){
					$row[$val]=trim($row[$val]);
					if($val=='第一作者'){
						$cont.=$row[$val];
					}
					else{
						$cont.=",".$row[$val];
					}
				}
				else{
					break;
				}
			}
			//期刊名、会议名
			$cont.=empty($row['被发表于'])?"":(".".trim($row['被发表于']));
			if(strstr($row['论文类型'],"期刊")){			
				
				//出版年份
				$cont .=empty($row['发表时间'])?"":(".".trim($row['发表时间']));
				
				//卷
				$cont.=empty($row['卷'])?"":(".".trim($row['卷'])."卷");

				//期
				$cont.=empty($row['期'])?"":((empty($row['卷'])?".":"").trim($row['期'])."期");

				//页码
				$cont.=empty($row['页码'])?"":(":".trim($row['页码']));

				$index+=1;
			
			}
			else{
				//会议地点
				$cont .= empty($row['会议地点'])?"":(".".trim($row['会议地点']));
				//会议时间
				$cont .=empty($row['发表时间'])?"":(".".trim($row['发表时间']));

				$index+=1;
			}	
		
		*/
			$cont.="[$index] ".$oneRecord;
			$cont.="<br/><br/>";	
	}

	$cont.="</body>";
	echo $cont;
	$word->save(); 
}

?>
